import axios from '../utils/axios'
import apis from '../apis/index'

const toTree = (data) => {
    var rs = {};
    for(var i=0;i<data.length;i++){
        var permission = data[i];
        // console.log(permission);
        if (permission.parentid==0) {
            permission.children = [];
            rs[permission._id]=permission;
        }
    }
    for(let i=0;i<data.length;i++){
        var permission = data[i];
        for(var key in rs){
            if (permission.parentid == key) {
                rs[key].children.push(permission)
            }
        }
    }
    return rs;
    // console.log(rs);
}


const getters = {
    allMenus(state){
        return toTree(state.allMenus);
    },
    allPermissions(state){
        return toTree(state.allPermissions);
    }
}
const state = {
    allMenus:[],
    allPermissions:[],
}
const mutations = {
    LOADALLMENUS(state,payload){
        state.allMenus = payload;
    },
    LOADALLPERMISSIONS(STATE,payload){
        state.allPermissions = payload
    }
}
const actions = {
    loadAllPermission({commit},payload){
        axios.get(apis.findAllPermission)
        .then((resp)=>{
            console.log(resp.data.allPermission);
            commit('LOADALLPERMISSIONS',resp.data.allPermission)
        })
    }
}

export default{
    getters,
    state,
    mutations,
    actions
}